package com.zrj.auth.core.userdetails.user;

import com.zrj.auth.pojo.dto.AuthUserDTO;
import com.zrj.auth.service.impl.SysUserServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author zhaorujie
 */
@Service("sysUserDetailsService")
@RequiredArgsConstructor
@Slf4j
public class SysUserDetailsServiceImpl implements UserDetailsService {
    private final SysUserServiceImpl sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDetails sysUserDetails = null;
        AuthUserDTO authUser = sysUserService.getAuthInfoByUsername(username);
        if (authUser != null) {
            sysUserDetails = new SysUserDetails(authUser);
        }
        if (sysUserDetails == null) {
            throw new UsernameNotFoundException("用不存在");
        } else if (!sysUserDetails.isEnabled()) {
            throw new DisabledException("该账号已被禁用");
        } else if (!sysUserDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定");
        } else if (!sysUserDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期");
        }
        return sysUserDetails;
    }
}
